package com.bto.solar.work.fdd.client;

import com.bto.solar.work.common.BizException;
import com.bto.solar.work.common.RedisService;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.utils.StringUtils;
import com.fasc.open.api.bean.base.BaseRes;
import com.fasc.open.api.config.HttpConfig;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.stratey.DefaultJsonStrategy;
import com.fasc.open.api.v5_1.client.OpenApiClient;
import com.fasc.open.api.v5_1.client.ServiceClient;
import com.fasc.open.api.v5_1.res.service.AccessTokenRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@RefreshScope
@Slf4j
@Service
public class FddBaseClient {
    @Value("${fdd.app-id}")
    private String appId;
    @Value("${fdd.app-secret}")
    private String appSecret;
    @Value("${fdd.server-url}")
    private String serverUrl;


    @Autowired
    private RedisService redisService;

    public OpenApiClient getFddOpenApiClient() {
        OpenApiClient openApiClient = new OpenApiClient(appId, appSecret, serverUrl);
        // http超时配置设置， 默认不设置超时时间
        // 如果不设置超时时间 该设置可忽略
        HttpConfig httpConfig = new HttpConfig();
        httpConfig.setConnectTimeout(1000000);
        httpConfig.setReadTimeout(1000000);
        openApiClient.setHttpConfig(httpConfig);

        // Json序列化策率，默认使用Jackson，如果要使用其他如FastJson,Gson等实现JsonStrategy接口即可
        // 如果使用默认该设置可以忽略
        openApiClient.setJsonStrategy(new DefaultJsonStrategy());

        return openApiClient;
    }

    /**
     * 获取法大大 请求 token
     */
    public String getFddAccessToken() {
        String fddToken = redisService.<String>getCacheObject(Constants.FDD_TOKEN);
        if (!StringUtils.isEmpty(fddToken)) {
            return fddToken;
        }
        ServiceClient serviceClient = new ServiceClient(getFddOpenApiClient());
        BaseRes<AccessTokenRes> accessToken = null;
        try {
            accessToken = serviceClient.getAccessToken();
        } catch (ApiException e) {
            throw new BizException("法大大 获取token 请求错误 {}", e.getMessage());
        }
        if(!accessToken.isSuccess()){
            throw new BizException("法大大 获取token 请求错误 {}", accessToken.getMsg());
        }

        String token = accessToken.getData().getAccessToken();
        redisService.setCacheObject(Constants.FDD_TOKEN, token, 10L, TimeUnit.MINUTES);
        log.info("Get Fdd  Access token {} ", token);
        return token;
    }

    /**
     * 判断报错信息
     */
    public void isResultSuccess(BaseRes<?> res, String signTaskId, String errorStr) {
        if (null == res) {
            throw new BizException(errorStr, signTaskId);
        } else if (!Constants.FDD_OK.equals(res.getCode())) {
            throw new BizException(errorStr + ": {}", signTaskId, res.getMsg());
        }
    }

    public void isResultSuccess(BaseRes<?> res, String errorStr) {
        if (null == res) {
            throw new BizException(errorStr);
        } else if (!Constants.FDD_OK.equals(res.getCode())) {
            throw new BizException(errorStr + ": {}", res.getMsg());
        }
    }


}
